package service.impl;

import bean.OrderInfo;
import dao.OrderInfoDao;
import impl.OrderInfoDaoImpl;
import service.OrderAndDetailService;
import util.DBHelper;
import util.ServerResponseResult;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * @classname:OrderAndDetailServiceImpl
 * @description:
 * @author: Mr.Z
 * @date: 2021/1/2 10:13
 * @version: 0.1
 * @since:1.8
 */
public class OrderAndDetailServiceImpl implements OrderAndDetailService {
    @Override
    public ServerResponseResult addOrder(Map<Integer, Integer> map, OrderInfo orderInfo) {
        Connection con = DBHelper.getCon();

        try {
            //传入连接
            OrderInfoDao orderInfoDao = new OrderInfoDaoImpl(con);
            //开启连接
            con.setAutoCommit(false);
            //获得自增id
            int orderId = orderInfoDao.addOrderInfo(orderInfo);
            //添加订单详细表
            //传入uid 购买商品id和商品数量
            orderInfoDao.addOrderAndDetail(orderId, map);
            //减少商品的数量
            map.forEach((k, v) -> {
                orderInfoDao.updateGoodNumberById(k, v);
                //库存为0  改为下架

            });
            //减少会员的钱
            if(orderInfo.getMid()!=-1){
                Integer mid = orderInfo.getMid();
                BigDecimal total = orderInfo.getTotal();
                BigDecimal result = total.multiply(new BigDecimal(-1));
                orderInfoDao.updateMemberBalanceById(result, mid);
            }

            con.commit();
            return ServerResponseResult.success();
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DBHelper.closeResources(con);
        }
        return ServerResponseResult.error();
    }
}
